<?php 
namespace Emos\Field;

use Emos\Common;

class Password extends AbstractControl {
    public $nullable = true;
    
    protected $algorithm = 'crypt';
    
    public function __construct($algorithm = null) {
        $this->algorithm = $algorithm;
    }    
    
    public function html() {
        
        if($this->value == '') {
            $visible = '';
        }
        else {
            $visible = '********';
        }
        return 
            //$this->value.'<br>'.
            "<input type='password' class='password' name='{$this->htmlName}' value='".Common::plain($visible)."' />";
    }
    
    public function update() {
        $post = $this->getPost();       

        if($post === null || trim($post) == '') {
            return array($this->dbName => new Db\SqlExpression("NULL"));             
        }
        elseif(preg_match('/^ \*+ $/x', $post)) {
            return array();
        }
        else {            
            return array($this->dbName => $this->encode($post));             
        }        
    }    
    
    protected function encode($password) {
        if($this->algorithm == 'crypt') {
            return crypt($password);
        }
        elseif($this->algorithm == 'md5') {
            return md5($password);
        }        
        else {
            return $password;
        }
    }
}